//
//  AppDelegate.m
//  HWanGame
//
//  Created by Chendaobin on 2019/8/23.
//  Copyright © 2019年 Chendaobin. All rights reserved.
//

#import "AppDelegate.h"
#import "HWTabBarController.h"
#import "WXApi.h"
//#define   WXAPP_ID   @"wxd77f800397b2c424"
#define   AppSecret  @"9fd5766c2e51139b0082d26157f7c0d7"
#import "HWLoginController.h"
#import "XMGWebViewController.h"
#import "HWAES128.h"
#import <TencentOpenAPI/TencentOAuth.h>



#define  cl_SDK_APPID  @"20f718c313e9"
//#define       JGcl_SDK_APPID   @"282241283bab2da67ff9756a"

#define       JGcl_SDK_APPID   @"1f63839426746d2f5d457827"


//引入JVERIFICATIONService.h头文件
#import "JVERIFICATIONService.h"
// 如果需要使用 idfa 功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>

#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/ASIdentifierManager.h>
//#import <JWVIPSDK/JWVIPSDK.h>

#import <DyTaskSdk/DyAdApi.h>




@interface AppDelegate ()<WXApiDelegate,TencentSessionDelegate,V2TIMSDKListener> {
    
    NSString *member_id; //推广id
    HWQQGameTypeController *qqGame;
    
}

/** QQ分享*/
@property(nonatomic, strong) TencentOAuth * tencentOAuth;
/** 许可*/
@property(nonatomic, strong) NSArray * permissions;

@property(strong,nonatomic) NSDictionary *dataDic;
@property(strong,nonatomic) NSString *chuagulaiStr; // 传过来的数据

@property(strong,nonatomic) HWHomeHttpManager *httpManager; // 传过来的数据

@property(nonatomic, strong) Reachability *netReachability;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"formalUrl"] isEqualToString:@""] && [[NSUserDefaults standardUserDefaults] objectForKey:@"formalUrl"] != nil) {
        HWOCGlobalConst.baseUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"formalUrl"];
        NSLog(@"域名========%@",HWOCGlobalConst.baseUrl);
    }else {
        self.httpManager = [[HWHomeHttpManager alloc] init];
        [self.httpManager getBaseUrlWithSuccess:^(NSString * urlString) {
            NSLog(@"域名========%@",urlString);
            HWOCGlobalConst.baseUrl = urlString;
            if([urlString rangeOfString:@"95php"].location != NSNotFound) {
            } else {
                [HWLocallyStoredData setUserID:@""];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userHeadImage"];
                [[NSUserDefaults standardUserDefaults] setObject:urlString forKey:@"formalUrl"];
            }
            HWOCGlobalConst.baseUrl = urlString;
        } failure:^(NSString * errorStr) {
            
        }];
    }
    
    
//    [JWVIPSDKConfigure initWithVIPAccount:@"" secret:@"" scheme:@""];
    
    
    NSLog(@"%@",[NSBundle currentLanguage]);
    NSLog(@"%@",[NSBundle currentLanguage]);
    
    
    // [WXApi registerApp:WXAPP_ID universalLink:nil];
    
    // [WXApi registerApp:appId universalLink:@"https://help.wechat.com/sdksample/"];
    
    
    //  [CLShanYanSDKManager initWithAppId:cl_SDK_APPID complete:nil];
    
    //
    //    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    //      pasteboard.string = @"uduuu";
    //
    //
    //    NSLog(@"%@",pasteboard.string);
    //
    
    //    CGFloat a= 85000;
    //
    //    for (int i = 0 ; i < 30; i++) {
    //        a = a*(1 + 0.21)+50000;
    //
    //    }
    //
    //
    //    NSLog(@"%f",a);
    //    NSLog(@"%f",a);
    //
    //
    
    
    [self encrypttheRequestedURL];
    
    [self storageCoidStr];
    
    
    
    //设置这个主要是为了 1 没有微信登录   0 代表有微信和QQ登录
    [HWLocallyStoredData setLogQQAndWeichat:@"1"];
    
    
    
    
    JVAuthConfig *config = [[JVAuthConfig alloc] init];
    config.appKey = JGcl_SDK_APPID;
    
    //   config.advertisingId = idfaStr;
    config.authBlock = ^(NSDictionary *result) {
        NSLog(@"初始化结果 result:%@", result);
    };
    [JVERIFICATIONService setupWithConfig:config];
    
//    [WXApi registerApp:weixiappId];
    [WXApi registerApp:weixiappId universalLink:@""];
    
    
    
    _tencentOAuth = [[TencentOAuth alloc]initWithAppId:QQAPPID andDelegate:self];
    
    
    
    //      _tencentOAuth.redirectURI = @"www.qq.com";
    //       _permissions = [NSArray arrayWithObjects:@"get_user_info",@"get_simple_userinfo", @"add_t", nil];
    //
    //  //  NSArray *permissions = [NSArray arrayWithObjects:kOPEN_PERMISSION_GET_INFO, kOPEN_PERMISSION_GET_USER_INFO, kOPEN_PERMISSION_GET_SIMPLE_USER_INFO, nil];
    //
    //       [_tencentOAuth authorize:_permissions inSafari:NO];
    //
    
    
    
    
    
    
    
    //  [NSThread sleepForTimeInterval:4];
    
    
    
    //    HWTabBarController *control = [[HWTabBarController alloc] init];
    //    self.window.rootViewController = control;
    //
    //    [self.window makeKeyAndVisible];
    //
    
//    if ([HWLocallyStoredData getLoginUserID].length > 0) {
//        HWGameLiveHttpManager *httpManager = [[HWGameLiveHttpManager alloc] init];
//        
//        [httpManager getGameLiveImInfoWithSuccess:^(NSDictionary * dic) {
//            NSLog(@"%@",dic);
//            //            HWUniversal.jsonstring
//            
//            [httpManager getGameLiveConfigWithSuccess:^(NSString * appId) {
//                [[V2TIMManager sharedInstance] initSDK:[appId intValue] config:[[V2TIMSDKConfig alloc] init] listener:self];
//                [[V2TIMManager sharedInstance] login:dic[@"live_uid"] userSig:dic[@"live_sign"] succ:^{
//                    
//                    V2TIMUserFullInfo *info = [[V2TIMUserFullInfo alloc] init];
//                    info.nickName = [HWLocallyStoredData getUserName];
//                    info.faceURL = [HWLocallyStoredData getUserFace];
//                    
//                    //                    info.customInfo = @{@"color":[HWUniversal JSONStringToDataWithJson:@"adsfaf"]};
//                    [[V2TIMManager sharedInstance] setSelfInfo:info succ:^{
//                        
//                    } fail:^(int code, NSString *desc) {
//                        
//                    }];
//                    
//                } fail:^(int code, NSString *desc) {
//                    NSLog(@"%@,code=%d",desc,code);
//                }];
//            } failure:^(NSString * error) {
//                
//            }];
//            
//        } failure:^(NSString * error) {
//            
//        }];
//        
//    }
    
    qqGame = [[HWQQGameTypeController alloc] init];
    [qqGame qqGameInit];
    self.netReachability = [Reachability reachabilityForInternetConnection];
    [self.netReachability startNotifier];
    
    return YES;
    
    
}
- (NetworkStatus)currentStatus {
    return [self.netReachability currentReachabilityStatus];
}
// 加载Url
- (void)encrypttheRequestedURL {
    
    //    [SDKXIngRequest  encryptionQingqiuUrlStr:EncryptionQingqiuxingYaoSDK success:^(id  _Nullable response) {
    //
    //          NSLog(@"%@",response);
    //
    //      } failure:^(NSString * _Nonnull error) {
    //
    //
    //           NSLog(@"%@",error);
    //
    //      }];
    
    
    
}





// 获取coid
- (void)storageCoidStr  {
    
    
    
    NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
    
    NSString *path2 = [NSString stringWithFormat:@"%@/%@", bundlePath, @"coid"];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    //        NSString *channel = @"";
    
    
    NSString *channel = [NSString string];
    if ([manager fileExistsAtPath:path2]) {
        
        NSArray *allPath =[manager subpathsAtPath:path2];
        //4.遍历所有的子路径
        for (NSString *subPath in allPath) {
            if ([subPath containsString:@"coid_"]) {
                channel = [subPath substringFromIndex:@"coid_".length];
                NSLog(@"文件夹名字%@+++",  channel);
            }
        }
    }
    
    if ([channel isEqual:@""]) {
        
        member_id = [NSString stringWithFormat:@"0"];
    } else {
        
        member_id = [NSString stringWithFormat:@"%@",channel];
        [HWLocallyStoredData setCode:member_id];
        
        
    }
    NSLog(@"有值吗++%@+++", member_id);
    
    
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    
    //   pasteboard.string = @"coid_100";
    //   pasteboard.string = @"text_100";
    //  pasteboard.string = @"";
    NSString *codeStr  = pasteboard.string;
    
    
    if (![[HWLocallyStoredData getCode]   isEqualToString:@""]) {
        
        return;
        
    }
    
    
    
    
    
    
    
    if (codeStr.length > 0  ) {
        
        if ([codeStr containsString:@"coid_"]) {
            
            
            
            NSString *  channel = [codeStr substringFromIndex:@"coid_".length];
            codeStr = [NSString stringWithFormat:@"%@",channel];
            [HWLocallyStoredData  setCode:codeStr];
            
            
        } else {
            
            [self requestshujuCode];
            
            
            
            
        }
        
        
        
        
    } else {
        
        [self requestshujuCode];
        
        
    }
    
    NSLog(@"%@",codeStr);
    NSLog(@"%@",codeStr);
    
    
    
    
    
    
    
    
}





// 发送网路请求
- (void)requestshujuCode {
    
    
    
    
    NSDictionary *parametes = @{
        @"ct" :  @"app",
        @"ios" : @"1",
        @"ac" : @"get_member",
        @"member_id":[HWLocallyStoredData getCode],
        
        
    };
    [HWWebUtils do3GetWithParameters:parametes progress:nil success:^(id response) {
        
        [SVProgressHUD dismiss];
        
        
        
        NSString *codeStr =  [NSString stringWithFormat:@"%@",response[@"code"]];
        if ([codeStr intValue] == 1) {
            
            NSString *coid = [NSString stringWithFormat:@"%@",response[@"data"]];
            
            [HWLocallyStoredData  setCode:coid];
            
            
            
        } else  {
            
            [HWLocallyStoredData  setCode:@"0"];
            
        }
        
        
        
    } failure:^(NSString *error) {
        [SVProgressHUD dismiss];
        
        [HWLocallyStoredData  setCode:@"0"];
    }];
    
    
    
    
    
}








- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options  {
    
    if ([url.host isEqualToString:@"sdkJumpTo"]) {
        if ([[HWLocallyStoredData getLoginUserID] isEqualToString:@""]) {
            [MBProgressHUD showError:@"请登录后重试"];
        } else {
            [HWUniversal pushControllerWithType:url.query urlString:@""];
        }
        return YES;
    }
    
    if ([url.host isEqualToString:@"sdkOneKeyLogin"]) {
        if ([[HWLocallyStoredData getLoginUserID] isEqualToString:@""]) {
            [MBProgressHUD showError:@"请登录后重试"];
        } else {
            NSString *userID   =    [HWLocallyStoredData getLoginUserID];
            NSString *encryStr = [HWAES128 AES128Encrypt:userID key:@"mtetbpryjhdxmnhx"];
            NSString *urlStr = [NSString stringWithFormat:@"%@%@%@",url.query,@"://sdkOneKeyLogin?",encryStr];
            
            
            NSURL *url = [NSURL URLWithString:urlStr];
            
            [[UIApplication  sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                
            }];
            
        }
        
        return YES;
    }
    
    if ([url.host isEqualToString:@"OpenMiniGame"]) {
        if ([[HWLocallyStoredData getLoginUserID] isEqualToString:@""]) {
            [MBProgressHUD showError:@"请登录后重试"];
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self->qqGame openMiniGame:url.query];
            });

        }
        
        return YES;
    }
    
    self.chuagulaiStr = url.query;
    
    
    // return [WXApi handleOpenURL:url delegate:self];
    
    
    if ([url.host isEqualToString:@"oauth"]){//微信登录
        return [WXApi handleOpenURL:url delegate:self];
        
    }  else if ([url.host isEqualToString:@"qzapp"]) {
        
        
        return [TencentOAuth HandleOpenURL:url];
        
        
    }else if ([url.host isEqualToString:@"platformId=wechat"]) {
        
        
        return  YES;
        
        
    }else if ([url.host isEqualToString:@"response_from_qq"]) {
        
        
        return  YES;
        
        
    }
        
    if ([[HWLocallyStoredData getLoginUserID] isEqualToString:@""]) {
        
        [MBProgressHUD showError:@"请登录后重试"];
        
        return YES;
    }
    
    NSString *userID   =    [HWLocallyStoredData getLoginUserID];
    NSString *encryStr = [HWAES128 AES128Encrypt:userID key:@"mtetbpryjhdxmnhx"];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@%@",self.chuagulaiStr,@"://SDKnews?",encryStr];
    //        NSURL *url = [NSURL URLWithString:urlStr];
    
    // http://demo.94php.com/applogin.php?goto
    
    NSString *fanwenStr = [NSString stringWithFormat:@"%@",urlStr];
    fanwenStr = [fanwenStr  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url1 = [NSURL URLWithString:fanwenStr];
    
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        
        [[UIApplication  sharedApplication] openURL:url1 options:nil completionHandler:^(BOOL success) {
            
        }];
        
    } else {
        
        NSLog(@"没有安装此APP");
    }
    
    //  return [WXApi handleOpenURL:url delegate:self];
    return  YES;
    
    
    
    
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
//    return [WXApi handleOpenURL:url delegate:self];
//}




//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
//    return [WXApi handleOpenURL:url delegate:self];
//}

- (void)onResp:(BaseResp *)resp{
    if([resp isKindOfClass:[SendAuthResp class]]){
        SendAuthResp *resp2 = (SendAuthResp *)resp;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"wxLogin" object:resp2];
        //        [[NSNotificationCenter defaultCenter] postNotificationName:@"wxLogin" object:nil userInfo:resp2.code];
    }else{
        NSLog(@"授权失败");
    }
}



- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{

    return [TencentOAuth HandleOpenURL:url];
}


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{

    return [TencentOAuth HandleOpenURL:url];
}


@end
